package py.com.sole.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import py.com.sole.dao.ProveedorDao;
import py.com.sole.dao.DaoFactory;

import py.com.sole.model.Proveedor;

public class ProveedorImpl implements ProveedorDao {
  
  EntityManager em = DaoFactory.getEm();
  
  @Override
  public Proveedor addProveedor(Proveedor proveedor) {
    
    try {
      em.getTransaction().begin();
      em.persist(proveedor);
      em.getTransaction().commit();
      return proveedor;
    } catch (Exception e) {
      //System.out.println("Error al intentar persistir "+e);
      e.printStackTrace();
      return null;
    }
    
  }
  
  @Override
  public void deleteProveedor(int id) {
    try {
      em.getTransaction().begin();
      em.remove(this.getProveedorById(id));
      em.getTransaction().commit();
      
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  
  @Override
  public void updateProveedor(Proveedor proveedor) {
    // TODO Auto-generated method stub
    try {
      em.getTransaction().begin();
      em.merge(this.getProveedorById(proveedor.getId()));
      em.getTransaction().commit();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  
  @SuppressWarnings("all")
  @Override
  public List<Proveedor> getProveedores() {
    return em.createQuery("SELECT p FROM Proveedor p WHERE p.activo=TRUE").getResultList();
  }
  
  @Override
  public Proveedor getProveedorById(int id) {
    return (Proveedor) em.createQuery("SELECT p FROM Proveedor p where p.id = " + id).getSingleResult();
  }
  
  @Override
  public Proveedor getProveedorByName(String value) {
    // TODO Auto-generated method stub
    try {
      Query q = em.createNamedQuery("Proveedor.findByRazonSocial");
      q.setParameter("razonSocial", value);
      return (Proveedor) q.getSingleResult();
    } catch (Exception e) {
      return null;
    }
    
  }
  
}
